package com.ddh.bankmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddh.bankmanager.common.BaseEntity;
import com.ddh.bankmanager.domain.customerinfo.CustomerInfo;
import com.ddh.bankmanager.domain.customerinfo.dto.CustomerInfoLoginDTO;
import com.ddh.bankmanager.domain.customerinfo.dto.CustomerInfoQueryDTO;
import com.ddh.bankmanager.domain.customerinfo.dto.CustomerInfoRegisterDTO;
import com.ddh.bankmanager.domain.customerinfo.vo.CustomerInfoVO;
import com.ddh.bankmanager.enum_.ResultCode;
import com.ddh.bankmanager.enum_.RoleEnum;
import com.ddh.bankmanager.enum_.StatusEnum;
import com.ddh.bankmanager.exception.ServiceException;
import com.ddh.bankmanager.mapper.CustomerInfoMapper;
import com.ddh.bankmanager.service.CustomerInfoService;
import com.ddh.bankmanager.service.RSAService;
import com.ddh.bankmanager.utils.JwtUtils;
import com.ddh.bankmanager.utils.ThreadLocalUtil;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
* @author 11
* @description 针对表【customer_info】的数据库操作Service实现
* @createDate 2025-02-25 10:51:26
*/
@Service
@Slf4j
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo>
    implements CustomerInfoService{

    @Resource
    private RSAService rsaService;

    @Override
    public CustomerInfo getCustomerInfoByUsername(String username) {
        LambdaQueryWrapper<CustomerInfo> userNameCondition = new LambdaQueryWrapper<CustomerInfo>()
                        .eq(CustomerInfo::getUsername, username);
        CustomerInfo customerInfo = this.getOne(userNameCondition);
        return customerInfo;
    }

    /**
     * 登录
     * @param customerInfoDTO
     * @return
     */
    @Override
    public CustomerInfoVO login(CustomerInfoLoginDTO customerInfoLoginDTO) {
        //1.查询用户是否存在
        CustomerInfo customerInfo = getCustomerInfoByUsername(customerInfoLoginDTO.getUsername());
        if (customerInfo == null) {
            throw new ServiceException(ResultCode.USERNAME_AND_PASSWORDERROR);
        }
        //2.判断密码是否正确
        //2.1加密密码  RSA加密
        String decryptPassword = rsaService.privateKeyDecrypt(customerInfo.getPassword());
        log.info("加密后密码是:{}", decryptPassword);
        if (!decryptPassword.equals(customerInfoLoginDTO.getPassword())){
            throw new ServiceException(ResultCode.USERNAME_AND_PASSWORDERROR);
        }
        //3.JWT
        HashMap<String, Object> map = new HashMap<>();
        map.put("customerId",customerInfo.getCustomerId());
        String token = JwtUtils.generateJwt(map);
        //4.数据脱敏
        CustomerInfoVO customerInfoVO = new CustomerInfoVO();
        BeanUtils.copyProperties(customerInfo, customerInfoVO);
        customerInfoVO.setToken(token);
        return customerInfoVO;
    }

    /**
     * 注册
     * @param customerInfoRegisterDTO
     * @return
     */
    @Override
    public Boolean register(CustomerInfoRegisterDTO customerInfoRegisterDTO) {
        //1.查询用户是否存在
        CustomerInfo customerInfo = getCustomerInfoByUsername(customerInfoRegisterDTO.getUsername());
        if (customerInfo != null) {
            throw new ServiceException(ResultCode.USERNAME_EXISTS);
        }
        //2.对密码进行加密
        String encryptPassword = rsaService.publicKeyEncryption(customerInfoRegisterDTO.getPassword());
        //3.注册
        customerInfo = new CustomerInfo();
        BeanUtils.copyProperties(customerInfoRegisterDTO, customerInfo);
        //默认姓名都叫张无忌
        customerInfo.setName("张无忌");
        customerInfo.setPassword(encryptPassword);
        customerInfo.setRole(RoleEnum.USER.getCode());
        customerInfo.setStatus(StatusEnum.DISABLE.getStatus());
        log.info("保存用户信息:{}", customerInfo);
        boolean save = save(customerInfo);
        return save;
    }

    /**
     * 获取客户信息列表
     * @param customerInfoQueryDTO
     * @return
     */
    @Override
    public BaseEntity<CustomerInfo> getCustomerInfoList(CustomerInfoQueryDTO customerInfoQueryDTO) {
        // 创建分页对象，current表示当前页，size表示每页显示的记录数
        Page<CustomerInfo> page = new Page<>(customerInfoQueryDTO.getPageNo(), customerInfoQueryDTO.getPageSize());

        // 可以创建QueryWrapper来添加查询条件，这里以无条件查询为例
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<CustomerInfo>()
                .eq(StringUtils.isNotBlank(customerInfoQueryDTO.getStatus()),CustomerInfo::getStatus, customerInfoQueryDTO.getStatus())
                .like(StringUtils.isNotBlank(customerInfoQueryDTO.getUsername()),CustomerInfo::getUsername, customerInfoQueryDTO.getUsername())
                .like(StringUtils.isNotBlank(customerInfoQueryDTO.getRole()),CustomerInfo::getRole, customerInfoQueryDTO.getRole());

        Page result = page(page, lambdaQueryWrapper);
        BaseEntity<CustomerInfo> baseEntity = new BaseEntity<>();
        baseEntity.setTotal(result.getTotal());
        baseEntity.setRecords(result.getRecords());
        baseEntity.setPageNo(result.getCurrent());
        baseEntity.setPageSize(result.getSize());
        // 执行分页查询
        return baseEntity;
    }

    /**
     * 删除客户信息
     * @param customerId
     * @return
     */
    @Override
    public Boolean deleteCustomerInfo(Integer customerId) {
        return removeById(customerId);
    }

    /**
     * 根据id查询客户信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerInfo getCustomerInfoById(Integer customerId) {
        return getById(customerId);
    }

    /**
     * 获取当前登录用户
     * @return
     */
    @Override
    public CustomerInfo current() {
        Integer customerId = ThreadLocalUtil.get("customerId");
        log.info("用户customerId:{}", customerId);
        System.out.println("用户customerId:"+customerId);
        if (customerId == null) {
            throw new ServiceException(ResultCode.UNAUTHORIZED);
        }
        CustomerInfo customerInfo = getById(customerId);
        return customerInfo;
    }
}




